package top.cardone.beans;

import com.google.common.base.Charsets;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.core.io.Resource;
import top.cardone.context.ApplicationContextHolder;

import java.io.InputStream;
import java.util.LinkedHashMap;

/**
 * Created by Administrator on 2015/5/22.
 */
public class JsonFileFactoryBean implements FactoryBean<Object> {
    @lombok.Setter
    private Resource jsonFile;
    @lombok.Setter
    @lombok.Getter
    private Class<?> objectType;
    @lombok.Setter
    @lombok.Getter
    private boolean singleton = true;

    @Override
    public Object getObject() throws Exception {
        if (jsonFile == null) {
            return null;
        }

        if (!jsonFile.exists()) {
            return null;
        }

        String json;

        try (InputStream inputStream = jsonFile.getInputStream()) {
            json = IOUtils.toString(inputStream, Charsets.UTF_8);
        }

        if (objectType == null) {
            return ApplicationContextHolder.func(Gson.class, gson -> gson.fromJson(json, new TypeToken<LinkedHashMap<String, Object>>() {
            }.getType()));
        }

        return ApplicationContextHolder.func(Gson.class, gson -> gson.fromJson(json, objectType));
    }
}
